package com.xbj.utils;

import com.xbj.model.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class FilterUtils implements Filter {


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request =(HttpServletRequest)servletRequest;
        String uri = request.getRequestURI();
        User user = (User)request.getSession().getAttribute(User.USERSESSION);
        boolean flag = false;

        if (user != null){
            flag = true;
        }  else if ((request.getContextPath()+ "/login").equals(uri) || uri.startsWith(request.getContextPath()+"/static/")|| uri.startsWith(request.getContextPath()+"/index")){
            flag = true;
        }

        if (flag){
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            ((HttpServletResponse)servletResponse).sendRedirect(request.getContextPath()+ "/login");
        }
    }

    @Override
    public void destroy() {
    }
}
